package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.User;
import com.example.forum.services.IUserService;
import com.example.forum.utils.MD5Util;
import com.example.forum.utils.StringUtil;
import com.example.forum.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.mail.EmailException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Timer;
import java.util.TimerTask;

@Slf4j
@Api(tags="用户接口")
@RequestMapping("/user")
@RestController
/**
 *用户调用的接口
 */
public class UserController {
    @Resource
    private IUserService userService;

    /**
     * 用户注册
     * @param username 注册的用户名
     * @param nickname 昵称
     * @param password 密码
     * @param passwordRepeat 确认密码
     * @return 返回是否注册成功
     */
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public AppResult register(@ApiParam("用户名")@RequestParam("username") @NonNull String username,
                              @ApiParam("昵称")@RequestParam("nickname")@NonNull String nickname,
                              @ApiParam("密码")@RequestParam("password")@NonNull String password,
                              @ApiParam("确认密码")@RequestParam("passwordRepeat")@NonNull String passwordRepeat,
                              @ApiParam("电子邮箱")@RequestParam("email")@NonNull String email,
                              @ApiParam("验证码")@RequestParam("verification_code")@NonNull String verification_code){
        if(!password.equals(passwordRepeat)){
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        System.out.println("+++++++++++++++++++++++++++++++++");
        //准备数据
        User user=new User();
        user.setUsername(username);
        user.setNickname(nickname);
        //处理密码
        //生成盐
        String salt= UUIDUtil.UUID_32();
        //生成密码的密文
        String encryptPassword= MD5Util.md5Salt(password,salt);
        //设置密码和盐
        user.setPassword(encryptPassword);
        user.setSalt(salt);
        //匹配验证码是否正确
        boolean flag= userService.judgmentverification_code(email,verification_code);
        if(flag==false){
           return AppResult.failed("验证码匹配不正确");
        }
        //验证码匹配正确
        user.setEmail(email);
        //调用Service层
        userService.createNormalUser(user);
        return AppResult.success();
    }
    @ApiOperation("验证码发送")
    @PostMapping("/verify")
    public AppResult verify(@ApiParam("用户名")@RequestParam("username") @NonNull String username,
                            @ApiParam("电子邮箱")@RequestParam("email")@NonNull String email) throws EmailException {
        User existsUser = userService.seleceByUserName(username);
        // 2.1 判断用户是否存在
        if (existsUser != null) {
            // 打印日志
            log.info(ResultCode.FAILED_USER_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }
        Timer t1=new Timer();
        userService.sendverify(email);
        t1.schedule(new TimerTask() {
            @Override
            public void run() {
                userService.deleteMap(email);
            }
        },120000);
        return AppResult.success("两分钟后验证码失效");
    }
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public AppResult login(HttpServletRequest request,
                           @ApiParam("用户名")@RequestParam("username")@NonNull String username,
                           @ApiParam("密码")@RequestParam("password")@NonNull String password){
        User user=userService.login(username,password);
        if(user==null){
            log.warn(ResultCode.FAILED_LOGIN.toString());
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }
        //如果输入的用户名和密码正确就把这个user设置到Session中
        HttpSession session=request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION,user);
        //返回结果
        return AppResult.success();
    }

    /**
     * 获取用户信息
     * @param request 可以从会话中获取
     * @param id 如果前端发送了id就从数据库中获取
     * @return
     */
    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public AppResult getUserInfo(HttpServletRequest request,
                                 @ApiParam("用户Id")@RequestParam(value = "id",required = false)Long id){
        User user=null;
        if(id==null){
            //如果id为空说明此时该用户已经登录因此我们可以从会话中获取到登录的用户
            HttpSession session=request.getSession(false);
            if(session==null){
                log.warn(ResultCode.FAILED_UNAUTHORIZED.toString());
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_UNAUTHORIZED));
            }
            user=(User) session.getAttribute(AppConfig.USER_SESSION);
        }else{
                //如果id不为空调用service层获取用户信息
            user=userService.selectById(id);
        }
        return AppResult.success(user);
    }

    /**
     * 实现退出登录
     * @param request 获取session对象
     * @return 返回成功
     */
    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request){
        //获取session对象判断当前是否是登录状态下
        HttpSession session=request.getSession(false);
        if(session!=null){
            log.info("退出登录");
            session.invalidate();
        }
        return AppResult.success("退出成功");
    }
    /**
     * 修改个人信息
     * @param username 用户名
     * @param nickname 昵称
     * @param gender 性别
     * @param email 邮箱
     * @param phoneNum 电话号
     * @param remark 个人简介
     * @return AppResult
     */
    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo (HttpServletRequest request,
                                 @ApiParam("用户名") @RequestParam(value = "username",required = false) String username,
                                 @ApiParam("昵称") @RequestParam(value = "nickname",required = false) String nickname,
                                 @ApiParam("性别") @RequestParam(value = "gender",required = false) Byte gender,
                                 @ApiParam("邮箱") @RequestParam(value = "email",required = false) String email,
                                 @ApiParam("电话号") @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                 @ApiParam("个人简介") @RequestParam(value = "remark",required = false) String remark){
        // 1. 接收参数
        // 2. 对参数做非空校验（全部都为空，则返回错误描述）
        if (StringUtil.isEmpty(username) && StringUtil.isEmpty(nickname)
                && StringUtil.isEmpty(email) && StringUtil.isEmpty(phoneNum)
                && StringUtil.isEmpty(remark) && gender == null) {
            // 返回错误信息
            return AppResult.failed("请输入要修改的内容");
        }
        //从session中获取用户id
        HttpSession session=request.getSession(false);
        User user=(User) session.getAttribute(AppConfig.USER_SESSION);

        // 3. 封装对象
        User updateUser = new User();
        updateUser.setId(user.getId()); // 用户Id
        updateUser.setUsername(username); // 用户名
        updateUser.setNickname(nickname); // 昵称
        updateUser.setGender(gender); // 性别
        updateUser.setEmail(email); // 邮箱
        updateUser.setPhoneNum(phoneNum); // 电话
        updateUser.setRemark(remark); // 个人简介

        //调用service中的方法
        userService.modifyInfo(updateUser);
        // 5. 查询最新的用户信息
        user = userService.selectById(user.getId());
        //将更新后的用户信息写入session中
        session.setAttribute(AppConfig.USER_SESSION, user);
        //返回结果
        return AppResult.success(user);
    }
    @ApiOperation("修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @ApiParam("原始密码")@RequestParam("oldPassword")@NonNull String oldPassword,
                                    @ApiParam("新密码")@RequestParam("newPassword")@NonNull String newPassword,
                                    @ApiParam("确认密码")@RequestParam("passwordRepeat")@NonNull String passwordRepeat){
        //检验新密码与确认密码是否相同
        if(!newPassword.equals(passwordRepeat)){
            //返回错误描述
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //获取当前登录的用户信息
        HttpSession session=request.getSession(false);
        User user=(User) session.getAttribute(AppConfig.USER_SESSION);
        //调用service
        userService.modifyPassword(user.getId(),oldPassword,newPassword);
        //销毁session
        if(session!=null){
            session.invalidate();
        }
        //返回结果
        return AppResult.success();
    }
}
